package cn.vendsystem.com.controller;


import cn.vendcommon.com.entity.InventoryItem;
import cn.vendcommon.com.entity.Machine;
import cn.vendcommon.com.entity.Result;
import cn.vendsystem.com.service.InventoryService;
import cn.vendsystem.com.service.MachineService;
import cn.vendsystem.com.utils.AliOssUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/inventory")
@Slf4j
public class InventoryController {

    @Resource
    private AliOssUtil aliOssUtil;
    @Resource
    private InventoryService inventoryService;
    @Resource
    private MachineService machineService;

    // 新增商品
    @PostMapping
    public Result<InventoryItem> addInventory(@RequestBody InventoryItem item) {
        // 查找货道是否存在
        Machine machine = machineService.getMachineById(item.getMachineId());
        if (machine == null) {
            return Result.error("货道不存在");
        }
        return Result.success(inventoryService.addInventory(item));
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public Result deleteInventory(@PathVariable int id) {
        int result = inventoryService.deleteInventory(id);
        if (result == 1) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    // 修改商品
    @PutMapping
    public Result<String> updateInventory(
            @RequestPart(value = "file",required = false) MultipartFile file,
            @ModelAttribute InventoryItem item) {
        // 查找货道是否存在
        Machine machine = machineService.getMachineById(item.getMachineId());
        if (machine == null) {
            return Result.error("货道不存在");
        }
        String oldPicture = inventoryService.getPictureById(item.getId());
        // 上传图片
        if (file != null && !StringUtils.hasText(item.getPicture()) || StringUtils.hasText(item.getPicture()) && !item.getPicture().equals(oldPicture)) {
            try {
                // 原始文件名
                String originalFilename = file.getOriginalFilename();
                // 截取原始文件名的后缀
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 构造新文件名称
                String objectName = "inventory/images/" + item.getName() + "_" + UUID.randomUUID() + extension;
                // 上传文件到 OSS
                String filePath = aliOssUtil.upload(file.getBytes(), objectName);
                // 删除旧图片
                aliOssUtil.delete(item.getPicture());
                item.setPicture(filePath);
            } catch (IOException e) {
                log.error("商品图片上传失败", e);
                return Result.error("上传失败");
            }
        }
        item.setPicture(oldPicture);
        inventoryService.updateInventory(item);
        return Result.success("更新成功");
    }

    // 根据ID查询商品
    @GetMapping("/{id}")
    public Result<InventoryItem> getInventoryById(@PathVariable int id) {
        InventoryItem item = inventoryService.getInventoryById(id);
        return item != null ? Result.success(item) : Result.error("商品不存在");
    }


    // 查询所有商品
    @GetMapping
    public Result<List<InventoryItem>> getAllInventory() {
        return Result.success(inventoryService.getAllInventory());
    }

    /**
     * 上传商品信息（文件 + 表单）
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadPictureAndInfo(
            @RequestPart(value = "file",required = false) MultipartFile file,
            @ModelAttribute InventoryItem item) {

        if (file == null || file.isEmpty()) {
            return Result.error("上传文件为空");
        }
        log.info("商品图片上传：商品={}，文件={}", item.getName(), file.getOriginalFilename());

        try {
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构造新文件名称
            String objectName = "inventory/images/" + item.getName() + "_" + UUID.randomUUID() + extension;

            // 上传文件到 OSS
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            item.setPicture(filePath);

            // 新增商品
            inventoryService.addInventory(item);

            // 返回上传后的 OSS 地址
            return Result.success(filePath);

        } catch (IOException e) {
            log.error("商品图片上传失败", e);
            return Result.error("上传失败");
        }
    }




}
